<?php

namespace app\xcxapi\service;

use app\common\service\BaseService;
use app\lib\exception\BaseException;
use app\models\ContractModel;
use app\models\CourseContractModel;
use app\models\CourseModel;
use app\models\DictionaryModel;
use app\models\FollowUpLogModel;
use app\models\GoodsContractModel;
use app\models\GoodsModel;
use app\models\GradesContractModel;
use app\models\GradesDetailsModel;
use app\models\MarkingModel;
use app\models\PayFlowModel;
use app\models\StudentModel;
use app\models\StudentSubjectClassModel;
use app\models\StudentSubjectInfosClassModel;
use app\xcxapi\validate\StudentValidate;

class StudentService extends BaseService
{
    /**
     * 验证
     *
     * @var StudentValidate
     */
    protected $studentValidate;

    /**
     * 学员列表
     * User: wufeng
     * Date: 2020/02/20.
     *
     * @param $params
     *
     * @return array
     */
    public function studentLists($params)
    {
        try {
            $where = [];

//            //时间段
//            if (isset($params['start_date']) && '' !== $params['start_date'] && isset($params['end_date']) && '' !== $params['end_date']) {
//                if (isset($params['status_type'])) {
//                    if ('' === $params['status_type']) {
//                        $where['update_time'] = ['between', [$params['start_date'].' 00:00:00', $params['end_date'].' 23:59:59']]; //最后操作时间
//                    } elseif ('2' === $params['status_type']) {
//                        $where['next_follow_up_record'] = ['between', [$params['start_date'], $params['end_date']]]; //下次待跟进时间
//                    } elseif ('3' === $params['status_type']) {
//                        $where['create_time'] = ['between', [$params['start_date'].' 00:00:00', $params['end_date'].' 23:59:59']]; //创建时间
//                    } elseif ('4' === $params['status_type']) {
//                        $where['birth'] = ['between', [$params['start_date'], $params['end_date']]]; //生日
//                    } elseif ('5' === $params['status_type']) {
//                        $where['register_date'] = ['between', [$params['start_date'], $params['end_date']]]; //登记日期
//                    }
//                }
//            }
			//获取学员列表[通过班级找学生]
			if(xcxapi_get_current_wtype() == 5){
				if(xcxapi_get_current_group_type() == 2){  //老师类
					$grades_res = (new GradesDetailsModel())->where(['user_teacher_id' => get_current_id()])->column('id');
					$grades_res_str = implode(',',$grades_res);
					$student_res = (new StudentSubjectClassModel())->where(['class_subject_id' => ['in',$grades_res_str]])->column('student_id');
					$student_res = array_unique($student_res);
					$student_id_one = $student_res;
					$student_res_str = implode(',',$student_res);
					$where['id'] = ['in',$student_res_str];
				}else if(xcxapi_get_current_group_type() == 3){  //助教类
					$grades_res = (new GradesDetailsModel())->where(['user_assistant_id' => get_current_id()])->column('id');
					$grades_res_str = implode(',',$grades_res);
					$student_res = (new StudentSubjectClassModel())->where(['class_subject_id' => ['in',$grades_res_str]])->column('student_id');
					$student_res = array_unique($student_res);
					$student_id_one = $student_res;
					$student_res_str = implode(',',$student_res);
					$where['id'] = ['in',$student_res_str];
				}else if(xcxapi_get_current_group_type() == 4){ //班主任
					$grades_res = (new GradesDetailsModel())->where(['user_master_id' => get_current_id()])->column('id');
					$grades_res_str = implode(',',$grades_res);
					$student_res = (new StudentSubjectClassModel())->where(['class_subject_id' => ['in',$grades_res_str]])->column('student_id');
					$student_res = array_unique($student_res);
					$student_id_one = $student_res;
					$student_res_str = implode(',',$student_res);
					$where['id'] = ['in',$student_res_str];
				}else if(xcxapi_get_current_group_type() == 5){ //教务类
					$where['user_edu_id'] = array(array('like','%'.get_current_id().'%'), array('eq',0), array('eq',null), 'or');
				}
			}else{
				$where['campus_id'] = ['in',xcxapi_get_current_campus_id()];
			}

			$where['is_audition'] = 2;
			$where['sign_up'] = 1;
            $this->data = (new StudentModel())
                ->where($where)
                ->order('id desc')
                ->select()
//				->paginate($listRows, false, ['page' => $page])
                ->toArray();

            if (empty($this->data)) {
                throw new BaseException('NO_DATA');
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 学员详情、学员跟进记录
     * User: wufeng
     * Date: 2020/02/20.
     *
     * @param $params
     *
     * @return array
     */
    public function studentDetail($params)
    {
        try {
            $where = [];
            $where['student_id'] = $params['id'];
            $this->data['log'] = (new FollowUpLogModel())
                ->where($where)
				->order('time desc')
                ->select()
                ->toArray()
            ;
            foreach ($this->data['log'] as &$log) {
                if (1 === (int) $log['type']) {
                    $log['type_text'] = '系统';
                    $log['avatar'] = '/img.jpg';
                } elseif (2 === (int) $log['type']) {
                    $log['type_text'] = xcxapi_get_current_name();
                    $log['avatar'] = xcxapi_get_current_img();
                }
                $log['follow_up'] = DictionaryModel::getById($log['follow_up'], 'name');
                $log['mode'] = DictionaryModel::getById($log['mode'], 'name');
                if ($log['intentional_grade'] < 3) {
                    $log['intentional_grade_text'] = '低';
                } elseif ($log['intentional_grade'] > 3) {
                    $log['intentional_grade_text'] = '高';
                } else {
                    $log['intentional_grade_text'] = '中';
                }
                $log['marks'] = (new MarkingModel())->where(['lid' => $log['id']])->select();
            }
            $this->data['detail'] = (new StudentModel())
                ->where(['id' => $params['id']])
                ->find()
            ;
            $this->data['detail']['tuition'] = ((new ContractModel())->where(['student_id' => $params['id']])->sum('balance')) / 100;
			$count = (new StudentSubjectInfosClassModel())->where('student_id',$params['id'])->count();
			if($count > 0){
				$this->data['detail']['is_timetable'] = "已排课";
			}else{
				$this->data['detail']['is_timetable'] = "未排课";
			}

        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 订单记录
     * User: wufeng
     * Date: 2020/02/20.
     *
     * @param $params
     *
     * @return array
     */
    public function orderRecord($params)
    {
        try {
			/**订单记录**/
			$Order_json = [];   //返回前台订单json
			$Flow_json = [];   //返回前台流水json
			$Stored_json = [];   //返回前台储值json
			$res = (new ContractModel())->where(['student_id' => $params['id']])->order('signing_date asc')->select();
			foreach ($res as $value){
				$Order_json_item = [];
				$Flow_json_item = [];
				$Stored_json_item = [];
				/*********直接报名************/
				//课程
				$res_course = (new CourseContractModel())->where(['contract_id' => $value['id'],  'student_id' => $params['id']])->select();
				foreach ($res_course as $value_course){
					$item_Order = [];
					$course_result = CourseModel::get(['id' => $value_course['course_id']]);
					$item_Order['project_name'] = $course_result['course_name']; //项目
					$item_Order['project_price'] = ($value_course['price']/100).'/'.$course_result['unit'];  //单价
					$item_Order['project_nums'] = $value_course['class_num'].'/'.$course_result['unit'];  //数量
					$item_Order['project_discount'] = ($value_course['direct_money'] + $value_course['assessed_amount'])/100; //优惠金额[直减 + 分摊];
					$item_Order['project_give_nums'] = $value_course['give_class_num'];  //赠送
					$item_Order['project_net_receipts'] = ($value_course['net_receipts'] - $value_course['assessed_amount'])/100; //应收
					$item_Order['project_actual'] = $value_course['payment'] / 100;  //实收
					$item_Order['project_arrears'] = ($item_Order['project_net_receipts'] - $item_Order['project_actual']);  //欠费
					$Order_json_item[] = $item_Order;
				}

				//班级
				$res_grades = (new GradesContractModel())->where(['contract_id' => $value['id'], 'student_id' => $params['id']])->select();
				foreach ($res_grades as $value_grades){
					$item_Order = [];
					$grades_result = GradesDetailsModel::get(['id' => $value_grades['grades_id']]);
					$course_result = CourseModel::get(['id' => $value_grades['course_id']]);
					$item_Order['project_name'] = $grades_result['grades_name']; //项目
					$item_Order['project_price'] = ($value_grades['price']/100).'/'.$course_result['unit'];  //单价
					$item_Order['project_nums'] = $value_grades['class_num'].'/'.$course_result['unit'];  //数量
					$item_Order['project_discount'] = ($value_grades['direct_money'] + $value_grades['assessed_amount'])/100; //优惠金额[直减 + 分摊];
					$item_Order['project_give_nums'] = $value_grades['give_class_num'];  //赠送
					$item_Order['project_net_receipts'] = ($value_grades['net_receipts'] - $value_grades['assessed_amount'])/100; //应收
					$item_Order['project_actual'] = $value_grades['payment'] / 100;  //实收
					$item_Order['project_arrears'] = ($item_Order['project_net_receipts'] - $item_Order['project_actual']);  //欠费
					$Order_json_item[] = $item_Order;
				}

				//物品
				$res_goods = (new GoodsContractModel())->where(['contract_id' => $value['id'], 'student_id' => $params['id']])->select();
				foreach ($res_goods as $value_goods){
					$item_Order = [];
					$goods_result = GoodsModel::get(['id' => $value_goods['goods_id']]);
					$item_Order['project_name'] = $goods_result['goods_name']; //项目
					$item_Order['project_price'] = ($value_goods['price']/100).'/'.$goods_result['unit'];  //单价
					$item_Order['project_nums'] = $value_goods['goods_num'].'/'.$goods_result['unit'];  //数量
					$item_Order['project_discount'] = ($value_goods['direct_money'] + $value_goods['assessed_amount'])/100; //优惠金额[直减 + 分摊];
					$item_Order['project_give_nums'] = '-';  //赠送
					$item_Order['project_net_receipts'] = ($value_goods['net_receipts'] - $value_goods['assessed_amount'])/100; //应收
					$item_Order['project_actual'] = $value_goods['payment'] / 100;  //实收
					$item_Order['project_arrears'] = ($item_Order['project_net_receipts'] - $item_Order['project_actual']);  //欠费
					$Order_json_item[] = $item_Order;
				}
				/*************流水***************/
				$res_receivables = (new PayFlowModel())->where(['contract_number' => $value['contract_number']])->select();
				foreach($res_receivables as $value_flowmodel){
					$item_Flow = [];
					$item_Flow['flow_number'] = $value_flowmodel['receipt_number'];  //流水号
					$item_Flow['flow_time'] = $value_flowmodel['create_time'];  //收款日期
					$item_Flow['flow_payment_method'] = DictionaryModel::get($value_flowmodel['pay_channel'])['name']; //支付方式
					$item_Flow['flow_amount'] = $value_flowmodel['amount']/100; //金额
					if($value_flowmodel['type'] == 1){
						$item_Flow['flow_type'] = '订单收入';
					}else if($value_flowmodel['type'] == 2){
						$item_Flow['flow_type'] = '订单退费';
					}
					$item_Flow['flow_remark'] = $value_flowmodel['remark']; //备注
					$Flow_json_item[] = $item_Flow;
				}

				/****************储值*****************/
				$item_Stored = [];
				$item_Stored['store_total_receipts'] =   ContractModel::where(['student_id' => $params['id']])->sum('storedvalue') /100; //总额
				$item_Stored['store_net_receipts'] = $value['storedvalue']/100;  //本次储值金额
				$item_Stored['store_surplus_money'] = StudentModel::get(['id' => $params['id']])['storedvalue'];
				$item_Stored['store_surplus_money'] = $item_Stored['store_surplus_money'] /100; //储值剩余总额
				$Stored_json_item[] = $item_Stored;

				$Order_json_item_ = [];
				$Order_json_item_['contract_number'] = $value['contract_number']; //订单号
				$Order_json_item_['signing_date'] = $value['create_time']; //签约日期
				$Order_json_item_['order_json'] = $Order_json_item; //订单详情
				$Order_json[] = $Order_json_item_;

				$Flow_json_item_ = [];
				$Flow_json_item_['contract_number'] = $value['contract_number']; //订单号
				$Flow_json_item_['signing_date'] = $value['create_time']; //签约日期
				$Flow_json_item_['flow_json'] = $Flow_json_item; //流水详情
				$Flow_json[] = $Flow_json_item_;

				$Stored_json_item_ = [];
				$Stored_json_item_['contract_number'] = $value['contract_number']; //订单号
				$Stored_json_item_['signing_date'] = $value['create_time']; //签约日期
				$Stored_json_item_['stored_json'] = $Stored_json_item; //储值详情
				$Stored_json[] = $Stored_json_item_;
			}

			$this->data['sign_up_order'] = $Order_json;  //报名订单
			$this->data['pay_flow'] = $Flow_json;  //流水订单
			$this->data['stored_value'] = $Stored_json; ;  //储值订单
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 就读记录
     * User: wufeng
     * Date: 2020/02/20.
     *
     * @param $params
     *
     * @return array
     */
    public function attendSchoolRecord($params)
    {
        try {
            $where = [];
            $where_ = [];
            $student_id = $params['id'];  //学生ID
            $where['student_id'] = $student_id;
            $where['campus_id'] = $where_['campus_id'] = (new StudentModel())->get($student_id)['campus_id'];
            $StudentSubjectClassModel = new StudentSubjectClassModel();
            $GradesDetailsModel = new GradesDetailsModel();
            $ContractModel = new ContractModel();
            $grades_res = $StudentSubjectClassModel->where($where)->column('class_subject_id');
            $grades_res = array_unique($grades_res);
            $grades_str = implode(',', $grades_res);

            //未结业还在就读 graduation_status 为0 就读；为1 过往
            $where_['id'] = ['in', $grades_str];

            //就读班级
            $this->data['attend_school'] = $GradesDetailsModel
				->where('graduation_status', 0)
				->where($where_)
				->order('id desc')
				->select()
                ->toArray();

            if (!empty($this->data['attend_school'])) {
                foreach ($this->data['attend_school'] as &$item) {
					$item['course_type'] = CourseModel::get(['id' => $item['course_id']])['course_type'];
                    $item['course_type_text'] = DictionaryModel::get(['id' => $item['course_type']])['name'];
                    $res = $ContractModel->where(['student_id' => $student_id])->order('signing_date asc')->find();
                    $item['sign_up_date'] = $res['signing_date'];
                    $item['already_grades_class'] = $item['already_arranged'].'/'.($item['already_class'] - $item['already_arranged']);
                    $item['total'] = $ContractModel->where(['student_id' => $student_id])->sum('balance') / 100;
					$item['room'] = (implode('|',array_unique(explode(',',$item['room_text']))));
                }
            }
            //过往班级
            $this->data['past_school'] = $GradesDetailsModel
				->where('graduation_status', 1)
				->where($where_)
				->order('id desc')
				->select()
                ->toArray();

            if (!empty($this->data['past_school'])) {
                foreach ($this->data['past_school'] as &$item) {
					$item['course_type'] = CourseModel::get(['id' => $item['course_id']])['course_type'];
                    $item['course_type_text'] = DictionaryModel::get(['id' => $item['course_type']])['name'];
                    $res = $ContractModel->where(['student_id' => $student_id])->order('signing_date asc')->find();
                    $item['sign_up_date'] = $res['signing_date'];
                    $item['already_grades_class'] = $item['already_arranged'].'/'.($item['already_class'] - $item['already_arranged']);
                    $item['total'] = $ContractModel->where(['student_id' => $student_id])->sum('balance') / 100;
					$item['room'] = (implode('|',array_unique(explode(',',$item['room_text']))));
                }
            }
        } catch (\Exception $e) {
            $this->errorMessage($e, $params);
        }

        return $this->return;
    }

    /**
     * 实例化
     * User: wufeng
     * Date: 2019/5/28.
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->studentValidate = new StudentValidate();
    }
}
